package com.luckdraw.service.game;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.Ioc;

import com.luckdraw.domain.Activity;

/**
 * 活动队列线程
 * @ClassName: GamePoolRunnable 
 * @author gaotaochen
 * @Description: 
 * @date 2017年1月18日 下午4:06:59 
 *
 */
public class GamePoolRunnable implements Runnable,GamePoolCallBack{
	
	private Ioc ioc;
	
	private Dao dao;
	
	/**
	 * 存储已结束的活动
	 */
	Set<Integer> setIds = new HashSet<Integer>();
	
	public GamePoolRunnable(Ioc ioc){
		this.ioc = ioc;
		this.dao = ioc.get(Dao.class);
	}

	public void run() {
		//已启动活动列表
		List<Activity> setList = dao.query(Activity.class, Cnd.where("status", "=", 1));
		boolean flag = true;//是否是第一次
		boolean b = true;
        while(b){
	        Cnd cnd = Cnd.where("status", "=", 1);
        	if(!flag){//第一次不剔除
        		//存储已启动的活动ID
        		List<Integer> setIdList = new ArrayList<Integer>();
	        	//剔除已启动活动池线程的活动
	        	for(Activity set:setList){
	        		//从已启动活动列表中剔除已结束的活动
	        		if(setIds.contains(Integer.valueOf(set.getId()))){
	        			setList.remove(set);
	        			setIds.remove(Integer.valueOf(set.getId()));
	        		}else{
	        			setIdList.add(set.getId());
	        		}
	        	}
	        	if(setIdList.size()>0){
	        		cnd.and("id", "NOT IN", setIdList.toArray());
	        	}
        	}else{
        		flag = false;
        	}
        	//查询待启动的活动
        	List<Activity> setList1;
        	try {
	        	setList1 = dao.query(Activity.class, cnd);
	        	//对每个活动启动一个线程维护活动池
	        	for(Activity set:setList1){
		        	GameRunnable gameRun = new GameRunnable(ioc, set.getId(),this);
		        	System.out.println("启动线程"+gameRun);
		        	new Thread(gameRun).start();
		        }
	        		//休眠10秒
        		Thread.sleep(10000);
        	} catch (InterruptedException e) { 
        	} catch (Exception e) {
        		System.out.println("活动队列异常终止，异常信息："+e.getLocalizedMessage());
        		b = false;
			}
        }
	}
	
	public void callBack(int setId){
		setIds.add(Integer.valueOf(setId));
	}
}
